import Pie from '@v/echarts/Pie.vue';
import qs from 'qs';
export default {
    name: 'Mydevice',
    components: {
        Pie,
    },
    data() {
        return {
            params: {
                search: '',
            },
            popData: [
                {
                    name: "deviceID",
                    cn: "设备编号",
                    value: "加载中..."
                }, {
                    name: "abnormalDevice",
                    cn: "设备状态",
                    value: "加载中..."
                },
                {
                    name: "serviceTime",
                    cn: "服务时间",
                    value: "加载中..."
                }, {

                    name: "longitude",
                    cn: "经度",
                    value: "加载中..."
                }, {
                    name: "latitude",
                    cn: "纬度",
                    value: "加载中..."
                }, {
                    name: "registered",
                    cn: "是否在线",
                    value: "加载中..."
                }
            ],
            show: false,
            style: {
                width: '100%',
                height: '55vh',
            },
            popStyle: {
                left: '0px',
                top: '0px'
            },
            data_info: [],
            //坐标点后，后台获取
            markersData: [],
            //坐标点，处理后的百度地图集合数据
            markers: [],
            //单点信息
            marker: new BMap.Point(116.417854, 39.921988),
            map: null,
            //信息窗口设置
            opts: {
                width: 250,//信息窗口宽度
                height: 80,//信息窗口高度
                title: "信息窗口",//信息窗口标题
                enableMessage: true,//设置允许信息窗发送信息
            },
            //自定义点图标
            myIconOn: new BMap.Icon(require("../../../static/onfill.png"), new BMap.Size(20, 29)),
            myIconOff: new BMap.Icon(require("../../../static/offill.png"), new BMap.Size(20, 29)),
            //地图中心点坐标设置
            mapData: {
                height: '100%',
                longitude: 121.281321,
                latitude: 31.13495
            },
            markerClusterer: '',
            activeName: 'first',
            paramsData: [

            ],
            listData: [
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                },
                {
                    clientId: 'ALX2019061001',
                    date: '2019-7-10',
                }
            ],
            pointTable: [],
            users: "",
            optionData: {
                temData: {
                    legendData: [],
                    seriesData: []
                },
            },
            userOptionData: {
                userData: {
                    legendData: [],
                    seriesData: []
                }
            },
            onlineCount: "",
            abnoramlCount: "",
            newparams: {
                search: '',
            },
            newData: [],
            pagesize: 10,
            currentPage: 1,
            total: 0,
            unactiveData: "",
            activeData: ""
        }
    },
    computed: {
        onlineOption() {
            var option = {
                legend: {
                    orient: 'vertical',
                    x: 'left',
                },
                color: ["#026cd2", "#01caff"],
                series: [{
                    name: '',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data: this.optionData.temData.seriesData,
                }]
            }
            return option;
        },
        expetionOption() {
            var option = {
                legend: {
                    orient: 'vertical',
                    x: 'left',
                },
                color: ["#6143fe", "#ffcc01"],
                series: [{
                    name: '设备异常',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data: [{
                        name: '',
                        value: 50,
                    },
                    {
                        name: '',
                        value: 30,
                    },
                    ]
                }]
            }
            return option;
        },
        userOption() {
            var option = {
                legend: {
                    orient: 'vertical',
                    x: 'left',
                },
                color: ["#f39b13", "#01caff","#ffcc01"],
                series: [{
                    name: '',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '30',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data: this.userOptionData.userData.seriesData
                }]
            }
            return option;
        },
    },
    watch: {
    },
    created() {

        //地图数据初始化
        this.initMap();
        this.onlineEchart();
        this.initalarmlist();
        this.userEchart();
    },
    mounted() {
        this.$nextTick(function () {
            //地图创建
            this.mapCreate();
            this.pointInit();
        });
    },
    methods: {
        //地图获取
        initMap() {
            //获取点信息
            var users = JSON.parse(window.localStorage.getItem("userInfo"));
            var listParamsObj = {
                uId: users.uId
            }
            this.$http.post('/deviceCommonInfoController/queryDeviceAP', qs.stringify(listParamsObj))
                .then((res) => {
                    if (res.status == 200) {
                      this.markersData = res.data;
                      this.pointInit();
                    } else {
                      this.markersData = [];
                      this.pointInit();
                    }
                }).catch((err) => {
                    console.log(err);
            });
        },
        //弹窗隐藏
        popHide() { this.show = false; },
        //判断绑定的属性
        handleClick(tab, event) { },
        //地图绘制
        mapCreate() {
            // 创建Map实例
            this.map = new BMap.Map("allmap");
            //设定地图中心点坐标和地图默认缩放级别
            this.map.centerAndZoom(new BMap.Point(this.mapData.longitude, this.mapData.latitude), 5);
            //开启滚轮播放
            this.map.enableScrollWheelZoom(true);
            //右上角缩放、移动
            this.map.addControl(new BMap.NavigationControl({
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                type: BMAP_NAVIGATION_CONTROL_SMALL
            }));
            var size = new BMap.Size(10, 20);
            this.map.addControl(new BMap.CityListControl({//切换城市
                anchor: BMAP_ANCHOR_TOP_LEFT,
                offset: size
            }));
            // 启用地图惯性拖拽，默认禁用。
            this.map.enableInertialDragging();
            // 启用连续缩放效果，默认禁用
            this.map.enableContinuousZoom();
            //定位控件
            this.map.addControl(new BMap.GeolocationControl());
            this.markerClusterer = new BMapLib.MarkerClusterer(this.map, {
                markers: [],
                maxZoom: 20
            });
            var _this = this;
            this.markerClusterer.__proto__._redraw = function () {

                this._clearLastClusters();
                this._createClusters();

                for (var i = 0, cluster; cluster = this._clusters[i]; i++) { //遍历所有的聚合点对象
                    cluster._clusterMarker.tag = i;
                    cluster._clusterMarker.onclick = function (e) { //在每个聚合点对象的视图对象上绑定事件
                        //这样就可以为每一个聚合点绑定点击事件了
                        _this.markersTag = e.target.tag;
                        var newArr = [];
                        console.log(e.target.tag);
                        _this.markerClusterer._clusters[e.target.tag]._markers.forEach((val, idx) => {
                            console.log(val);
                            newArr.push(val.content)
                        });
                        _this.pointTable = newArr;
                    }
                }
            }
        },
        //打点初始化
        pointInit() {
            // 循环删除点
            this.markers.forEach((point, idx) => {
                this.map.removeOverlay(point);
            });
            this.markerClusterer.clearMarkers();
            this.markers = [];
            //处理新点数据
            if (this.markersData == null) {
                this.$message.error("没有设备AP信息");
                return false;
            } else {
                this.markersData.forEach((point, idx) => {
                    console.log("point2", point);
                    if (point.latitude == undefined && point.longitude == undefined && point.latitude == "" && point.longitude) {
                        return false;
                    } else if (point.latitude != undefined && point.longitude != undefined) {
                        if (point.registered) {
                            this.marker = new BMap.Marker(new BMap.Point(point.longitude, point.latitude), { icon: this.myIconOn });
                        } else {
                            this.marker = new BMap.Marker(new BMap.Point(point.longitude, point.latitude), { icon: this.myIconOff });
                        }
                        //单点注入相关信息
                        this.marker.content = {
                            deviceID: point.deviceID,
                            latitude: point.latitude,
                            longitude: point.longitude,
                            abnormalDevice: point.abnormalDevice,
                            serviceTime: point.serviceTime ? point.serviceTime : "",
                            registered: point.registered ? "在线" : "离线",
                        };
                        // 将标注添加到地图中
                        this.map.addOverlay(this.marker);
                        //注入标注集合
                        this.markers.push(this.marker);
                    }
                    //单点绑定移入显示信息框事件
                    var _this = this;
                    this.marker.addEventListener("click", function (e) {
                        _this.show = false;
                        setTimeout(function () {
                            _this.popStyle.left = (e.clientX - 200) + 'px';
                            _this.popStyle.top = (e.clientY - 50) + 'px';
                            if (e.clientY > 320) {
                                _this.popStyle.top = '320px'
                            }
                            _this.show = true;
                            _this.popData.forEach(function (val, idx) {
                                console.log("2132", val);
                                for (var key in e.target.content) {
                                    if (val.name == key) {
                                        val.value = e.target.content[key]
                                    }
                                }
                            })
                        }, 300);
                    })
                });
                //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
                this.markerClusterer.addMarkers(this.markers)
                this.map.centerAndZoom(new BMap.Point(this.mapData.longitude, this.mapData.latitude), 5);
            }
        },
        registeredFormatter(row, column, cellValue, index) {
            return cellValue;
        },
        //设备统计饼图
        onlineEchart() {
            var users = JSON.parse(window.localStorage.getItem("userInfo"));
            var paramsEchart = {
                uId: users.uId
            }
            this.$http.post('/deviceCommonInfoController/deviceCount', qs.stringify(paramsEchart))
                .then((res) => {
                    if (res.status == 200) {
                        var seriesData = [];
                        for (var key in res.data) {
                            //console.log(key);
                            var newObj = {
                                value: '',
                                name: '',
                            };
                            newObj.value = res.data[key]
                            newObj.name = ""
                            seriesData.push(newObj);
                        }
                        //console.log(newObj);
                        //console.log(seriesData);
                        this.onlineCount = res.data.deviceOnLine;
                        this.abnoramlCount = res.data.deviceOffLine;
                        this.optionData.temData.seriesData = seriesData
                    }
                }).catch((err) => {
                    console.log(err);
            });
        },
        //用户统计
        userEchart() {
            var users = JSON.parse(window.localStorage.getItem("userInfo"));
            this.$http.get('/userController/userStatistics?uId=' + users.uId)
                .then((res) => {
                    if (res.status == 200) {
                        var userseriesData = [];
                        for (var key in res.data) {
                            var newObj = {
                                value: '',
                                name: '',
                            };
                            newObj.value = res.data[key];
                            newObj.name = ""
                            userseriesData.push(newObj);
                        }
                        console.log(newObj);
                        console.log(userseriesData)
                        this.activeData = res.data.activate;
                        this.unactiveData = res.data.nonactivated;
                        this.userOptionData.userData.seriesData = userseriesData
                    }
                }).catch((err) => {
                console.log(err);
            });
        },
        initalarmlist() {
          var users = JSON.parse(window.localStorage.getItem("userInfo"));
          this.$http.get('/alarmRecord/abnormalBar?userId=' + users.uId + "&limit=" + this.pagesize + "&deviceID=" + this.params.search)
             .then((res) => {
                if (res.status == 200) {
                    this.paramsData = res.data;
                    this.total = res.total;
                 }
              }).catch((err) => {
              console.log(err);
            });
        },
        handleChangeClick(val) {
            this.params.search = val;
            this.initalarmlist();
        },
        handleNewParamsClick(val) {

        },
        handleClick(tab) {
            if (tab.name == "first") {
                this.initalarmlist();
            } else if (tab.name == "second") {
                var users = JSON.parse(window.localStorage.getItem("userInfo"));
                var postData = {
                    uId: users.uId
                }
                this.$http.post("/deviceCommonInfoController/queryNewDevice", qs.stringify(postData))
                  .then((res) => {
                     if (res.status == 200) {
                        this.newData = res.data;
                     }
                    }).catch((err) => {
                    console.log(err);
                });
            } else if (tab.name == "third") {

            }
        },
        handleSizeChange(val) {
            this.pagesize = val;
            this.initalarmlist();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.initalarmlist();
        }
    },
}